var mongoose = require('mongoose');
var News = require('../models/comment.model');

exports.create = function(req,res,next){
    const news = new News(req.body);
    news.save(function (err,data) {
        if (err) {
          console.log(err);
        } else {
          res.json(data);
        }
      });

}

exports.update = function(req,res,next){
    const id = req.params.id;
    // 从User这个数据模型里去找ID的对象并且将它进行更新操作
    News.findByIdAndUpdate(id, {$set: req.body},{new:false})
    .then(data=>{
        // 这个data数据返回的是没有修改之前的数据
        res.json(data);
    })
}

exports.remove = function(req,res,next){
    const id = req.params.id;
    // 从User这个数据模型里去找ID的对象并且将它进行更新操作
    News.findByIdAndRemove(id, function(err,data){
        res.json({"message":"delete ok"});
    })
}
exports.removes=function(req,res,next){
    var ids=req.body.ids;
    if(ids.length>0){
        News.remove({
            _id:{$in: ids}
        }).then(data=>{
            res.json({'message':'delete ok'})
        })
    }
}

exports.list = function(req,res,next){
    var page = (req.body.page) ? req.body.page: 1;
    var limit = (req.body.limit) ? req.body.limit: 2;
    console.log(typeof(req.params))
    // console.log(req.param)
    console.log(req.params)
    var queryCondition = {};
    
    // if(req.params.id && req.params.id.trim().length>0){
    //     queryCondition = {
    //          "newsId": req.params.id
    //     };
        
    // }
    
    if(req.body.name && req.body.name.trim().length>0){
        title = req.body.name;
        queryCondition = {
            "title": new RegExp(title,"i")
        }
    }
    News.paginate(queryCondition,{page: page,limit:limit},function(err,results){
        console.log(results)
        res.json(results)
    })
 
 }